﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SJ.Platform.Common;
using SJ.Platform.EFCore.Common;
using SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Project;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.ProjectManager;
using SJ.Platform.Extend.IOC.CurrentUser;
using SJ.Platform.Extend.ModelExtend;
using SJ.Platform.Extend.ModelExtend.ProjectExt;
using SJ.Platform.Extend.Request;
using SJ.Platform.Extend.Response;

namespace SJ.Platform.Api.Controllers.ProjectManager
{
    /// <summary>
    /// 项目团队资源操作类
    /// </summary>
    [Route(GlobalVariableHandle.Scope_Api + "/ProjectTeam")]
    [ApiController]
    [Authorize(GlobalVariableHandle.Scope_Api)]
    public class ProjectTeamController : ControllerBase
    {
        private readonly SJDBContext _context;
        private readonly ICurrentUser _currentUser;
        private readonly Project_Team_MainHandle _teamMainHandle;
        private readonly Project_Team_MemberHandle _teamMemberHandle;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库</param>
        /// <param name="currentUser">当前用户</param>
        public ProjectTeamController(SJDBContext dbContext, ICurrentUser currentUser)
        {
            _context = dbContext;
            _currentUser = currentUser;
            _teamMainHandle = new Project_Team_MainHandle(dbContext);
            _teamMemberHandle = new Project_Team_MemberHandle(dbContext);
        }

        /// <summary>
        /// 获取所有项目团队
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("GetProjectTeamsAsync")]
        public async Task<IActionResult> GetProjectTeamsAsync([FromBody] ApiPageQueryRequest<ProjectTeamMainExtend> request)
        {
            try
            {
                var result = await _teamMainHandle.GetProjectTeamMainsAsync((int)request.PageIndex, (int)request.PageSize, _currentUser.UserId, ApiPageQueryRequest<ProjectTeamMainExtend>.GenerateCondition(request.Condition));

                return Ok(ApiPageQueryResponse<List<ProjectTeamMainExtend>>.SetResponse(ApiResponseStatus.Success, "查询成功", (int)request.PageIndex, (int)request.PageSize, result.count, result.mainExtends)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiPageQueryResponse<List<ProjectTeamMainExtend>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, (int)request.PageIndex, (int)request.PageSize, 0, new List<ProjectTeamMainExtend> { }));
            }
        }

        /// <summary>
        /// 根据主记录ID获取团队资源详情
        /// </summary>
        /// <param name="mId"></param>
        /// <returns></returns>
        [HttpGet("GetTeamMembersByMIdAsync/{mId}")]
        public async Task<IActionResult> GetTeamMembersByMIdAsync(string mId)
        {
            try
            {
                ProjectTeamMainExtend teamMain = await _teamMainHandle.GetEntityByIdAsync(mId);
                List<ProjectTeamMember> members = await _teamMemberHandle.GetTeamMembersByMIdAsync(mId);
                if (teamMain.Members == null)
                {
                    teamMain.Members = new List<ProjectTeamMember>();
                }
                teamMain.Members = members;
                return Ok(ApiNormalResponse<ProjectTeamMainExtend>.SetResponse(ApiResponseStatus.Success, "查询成功", teamMain)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<ProjectTeamMainExtend>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new ProjectTeamMainExtend { }));
            }
        }

        /// <summary>
        /// 根据项目ID获取团队成员
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        [HttpGet("GetTeamMembersByProjectIdAsync/{projectId}")]
        public async Task<IActionResult> GetTeamMembersByProjectIdAsync(string projectId)
        {
            try
            {
                ProjectTeamMainExtend teamMain = await _teamMainHandle.GetEntityByProjectIdAsync(projectId);
                List<ProjectTeamMember> members = await _teamMemberHandle.GetTeamMembersByProjectIdAsync(projectId);
                if(teamMain.Members==null)
                {
                    teamMain.Members = new List<ProjectTeamMember>();
                }
                teamMain.Members = members;
                return Ok(ApiNormalResponse<ProjectTeamMainExtend>.SetResponse(ApiResponseStatus.Success, "查询成功", teamMain)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<ProjectTeamMainExtend>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new ProjectTeamMainExtend { }));
            }
        }

        /// <summary>
        /// 制定项目团队资源
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("FormulateProjectTeamAsync")]
        public async Task<IActionResult> FormulateProjectTeamAsync([FromBody] ProjectTeamMainExtend model)
        {
            try
            {
                bool result = await TransactionHandle.ExecuteInTransactionAsync<bool>(_context, async () =>
                {
                    //先清空之前的记录
                    bool actionResult = await _teamMainHandle.DeleteByProjectIdAsync(model.ProjectId) && await _teamMemberHandle.DeleteByProjectIdAsync(model.ProjectId);

                    //主记录
                    ProjectTeamMain teamMain = model.ExtMapToEntity<ProjectTeamMain, ProjectTeamMainExtend>();
                    teamMain.Status = 1;
                    teamMain.AddTime = teamMain.AddTime == null ? DateTime.Now : teamMain.AddTime;
                    teamMain.AddUserId = string.IsNullOrWhiteSpace(teamMain.AddUserId) ? _currentUser.UserId : teamMain.AddUserId;
                    teamMain.EditUserId = _currentUser.UserId;
                    teamMain.EditTime = DateTime.Now;

                    foreach(ProjectTeamMember member in model.Members)
                    {
                        member.AddTime = teamMain.AddTime == null ? DateTime.Now : teamMain.AddTime;
                        member.AddUserId = string.IsNullOrWhiteSpace(teamMain.AddUserId) ? _currentUser.UserId : teamMain.AddUserId;
                        member.EditUserId = _currentUser.UserId;
                        member.EditTime = DateTime.Now;
                    }

                    //保存新的记录
                    actionResult = await _teamMainHandle.CreateAsync(teamMain) && await _teamMemberHandle.BatchCreateAsync(model.Members);
                    
                    return actionResult;
                });

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "项目团队资源添加" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "项目团队资源添加失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 根据项目ID获取团队成员
        /// </summary>
        /// <param name="mainId"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [HttpGet("UpdateTeamMainStatusAsync/{mainId}/{status}")]
        public async Task<IActionResult> UpdateTeamMainStatusAsync(string mainId, int status)
        {
            try
            {
                var result = await _teamMainHandle.UpdateTeamMainStatusAsync(mainId, status);

                return Ok(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.Success, "状态更新成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<ProjectTeamMainExtend>.SetResponse(ApiResponseStatus.BadRequest, "状态更新失败：" + ex.Message, new ProjectTeamMainExtend { }));
            }
        }
    }
}
